﻿using System.Windows.Input;

namespace Gavel.Common.Component.Model;

/// <summary>
/// 中继命令
/// </summary>
/// <param name="execute">执行命令</param>
/// <param name="canExecute">命令可执行</param>
/// <typeparam name="T">命令入参泛型</typeparam>
public class RelayCommand<T>(Action<T> execute, Func<T, bool>? canExecute = null) : ICommand
{
    /// <summary>
    /// 命令可执行
    /// </summary>
    /// <param name="parameter">入参</param>
    /// <returns>命令可执行</returns>
    public bool CanExecute(object? parameter) => parameter is T t && (canExecute?.Invoke(t) ?? true);

    /// <summary>
    /// 命令执行
    /// </summary>
    /// <param name="parameter">入参</param>
    public void Execute(object? parameter)
    {
        if (parameter is not T t)
        {
            return;
        }

        execute(t);
    }

    /// <summary>
    /// 命令执行事件绑定/解绑
    /// </summary>
    public event EventHandler? CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}